package com.hugong.yxx.wksp.modules.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hugong.yxx.wksp.common.bean.CodeBean;
import com.hugong.yxx.wksp.common.bean.JSONResult;
import com.hugong.yxx.wksp.common.bean.UserBean;
import com.hugong.yxx.wksp.common.utils.HttpContextUtils;
import com.hugong.yxx.wksp.common.utils.Setting;
import com.hugong.yxx.wksp.modules.controller.UserController;
import com.hugong.yxx.wksp.modules.service.OAuthApiService;
import com.hugong.yxx.wksp.persistence.entity.User;
import com.hugong.yxx.wksp.persistence.mapper.UserMapper;
import com.hugong.yxx.wksp.modules.service.IUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2019-08-13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    static Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private OAuthApiService oAuthApiService;
    @Autowired
    private UserMapper userMapper;

    @Override
    public String redirectUrl() {
        return oAuthApiService.authorize();
    }

    @Override
    public UserBean getUser(Object parame) throws Exception {
        return oAuthApiService.getUser(parame);
    }

    @Override
    public JSONResult weixinLogin(Object parame) throws Exception {
        UserBean userBean = oAuthApiService.getUser(parame);
        User user = User.getUserByUserBean(userBean);
        user.insert();
        return JSONResult.renderSuccess();
    }

    @Override
    public JSONResult messageLogin(String cellphone, String code) {
        CodeBean cb = (CodeBean) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("codeBean");
        if (ObjectUtil.isNull(cb)){
            return JSONResult.renderError("验证码登录超时！");
        }
        if (cellphone.equals(cb.getCellphone()) && code.equals(cb.getCode())){
            return JSONResult.renderSuccess();
        }
        return JSONResult.renderError("验证码验证失败！");
    }

    @Override
    public JSONResult addUser(String username, String code, String password) {
        User user =new User();
        List<User> users = userMapper.selectList(new EntityWrapper<User>()
                .eq("username",username)
                .eq("registerType",Setting.PHONE_REGISTER));
        if (!CollectionUtils.isEmpty(users)){
            return JSONResult.renderError("该账号已经被注册过！");
        }
        user.setRegisterType(Setting.PHONE_REGISTER);
        user.setUsername(username);
        user.setPassword(password);
        user.setCellphone(username);
        user.insert();
        return JSONResult.renderSuccess();
    }
}
